package com.aaa.filter;

import cn.hutool.core.util.ObjectUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ：XiaoXuan
 * @date ：Created in 2022/9/7 10:43
 * @description：登录认证过滤器
 * @modified By：
 * @version: 1.0
 */
//拦截所有的请求
@WebFilter("/*")
public class LogInFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //如果用户未登录，拦截，并让他去登录页面
        HttpServletRequest myRequest = (HttpServletRequest) request;
        String contextPath = myRequest.getContextPath();
        HttpServletResponse myResponse = (HttpServletResponse) response;
        HttpSession session = myRequest.getSession();
        //排除不需要拦截的资源
        String uri = myRequest.getRequestURI();
        if (uri.contains("login")||uri.contains("front")||uri.contains("static")) {
            chain.doFilter(request, response);
        } else {
            Object userObj = session.getAttribute("user");
            //如果用户已经登录，放行
            if (ObjectUtil.isNotEmpty(userObj)) {
                chain.doFilter(request, response);
            } else {
                myResponse.sendRedirect( contextPath+"/views/login.jsp");
            }
        }


    }

    @Override
    public void destroy() {
    }
}
